package kuangshen.syn;

/**
 * @program: liangt
 * @description: 取钱展示线程不安全
 * @author: liangt
 * @create: 2021-03-03 14:58
 */
public class UnSynDrawingMoney {

    public static void main(String[] args) {
        Account account = new Account(100,"存款");

        Draw draw = new Draw(account,50,0);
        Draw d2 = new Draw(account,100,0);

        draw.setName("你");
        d2.setName("我");
        draw.start();
        d2.start();
    }


}

class Account{
    public int money;
    public String name;

    public Account(int money,String name){
        this.name = name;
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
}

class Draw extends Thread{
    public Account account;
    public int drawMonry;
    public int nowMoney;
    public Draw(Account account,int drawMonry,int nowMoney){

        this.account = account;
        this.drawMonry = drawMonry;
        this.nowMoney = nowMoney;
    }

    public void draw(){
        if (account.money - drawMonry < 0){
            System.out.println(this.getName() +" 取钱时，余额不足！");
            return;
        }

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        account.money = account.money - drawMonry;
        nowMoney += drawMonry;
        System.out.println("卡里余额："+account.money);
        System.out.println(this.getName()+"手里现在有："+nowMoney);
    }


    @Override
    public void run(){
        draw();
    }
}
